<?php
define('ROOT_PATH', dirname(dirname(dirname(dirname(__FILE__)))) . '/');
$basename = basename($_SERVER['SCRIPT_FILENAME']);
$basename = explode('.',$basename );
define('CURSCRIPT', reset($basename));
include ROOT_PATH.'inc/class/application.class.php';
application::init();

include_once 'XiaoChengXu.class.php';
$xiaochengxu = new XiaoChengXu();

$xml = file_get_contents('php://input');
if (!empty($xml)) {
    $data = $xiaochengxu->xmlToArray($xml);
    if ('SUCCESS' == $data['return_code'] // 通信成功
        && 'SUCCESS' == $data['result_code']) // 业务成功
    if ($xiaochengxu->checkSign($data)) { // 检查签名
        $type = 'xiaochengxu_pay'; // 小程序支付

        $transaction_id = $data['transaction_id']; // 微信支付订单号
        $out_trade_no = $data['out_trade_no']; // 商户订单号
        $money = intval($data['total_fee']);
        $pay_res = DB::fetch_first("SELECT `uid`, `fee`, `pay`, `stype` FROM " . DB::table('x_pay_log') . " WHERE `type` = '" . $type . "' AND `out_trade_no` = '" . $out_trade_no . "'");
        if (!empty($pay_res)) {
            if ($pay_res['fee'] == $money) { // 检查支付金额
                if (0 == $pay_res['pay']) {
                    // 更新订单状态
                    DB::update('x_pay_log',
                        array(
                            'order_no' => $transaction_id,
                            'pay' => 1,
                            'paytime' => TIMESTAMP
                        ),
                        array(
                            'type' => $type,
                            'out_trade_no' => $out_trade_no
                        )
                    );

                    $uid = $pay_res['uid']; // 用户升级为VIP
                    $stype = $pay_res['stype']; // 升级VIP的类型
                    $expire = DB::result_first("SELECT `expire` FROM " . DB::table('pdd_vip_setting') . " WHERE `stype` = '" . $stype . "'");
                    DB::update('member', array('vip' => 1, 'vip_expire' => TIMESTAMP + $expire), array('uid' => $uid));
                }

                $ret = array(
                    'return_code' => 'SUCCESS',
                    'return_msg' => 'OK'
                );

                echo $xiaochengxu->xml_encode($ret);
                exit;
            }
        }
    }
}

$ret = array(
    'return_code' => 'FAIL',
    'return_msg' => 'ERROR'
);

echo $xiaochengxu->xml_encode($ret);
?>
